/*
 * mfc codec encoding example application
 * Andrzej Hajda <a.hajda@samsung.com>
 *
 * Main file of the application.
 *
 * Copyright 2012 Samsung Electronics Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <semaphore.h>

#include "common.h"
#include "args.h"
#include "in_demo.h"
#include "in_camera.h"
#include "in_uvc.h"
#include "out_file.h"
#include "io_dev.h"
#include "mfc.h"
#include "fimc.h"
#include "v4l_dev.h"

static pthread_t h264_process_tid;
static struct io_dev *chain[4] = {NULL,};
static sem_t wait_sem;

static void *h264_process_thread(void *pVoid)
{
	process_chain(chain, array_len(chain));
	sem_post(&wait_sem);

	return NULL;

}

int wait_h264_finish()
{
	sem_wait(&wait_sem);
	return 0;
}

int h264_init(struct options option)
{

	struct io_dev *input;
	struct io_dev *mfc;
	struct io_dev *fimc;

	struct io_dev *output;

	sem_init(&wait_sem, 0, 0);
	input = in_demo_create(option.in_width, option.in_height);

	if (input == NULL)
		return 1;
	chain[0] = input;

	input->io[DIR_OUT].limit = option.duration;

	fimc = fimc_create(option.fimc_name);
	if (fimc == NULL)
		return 1;
	chain[1] = fimc;

	fimc->io[DIR_IN].limit = option.duration;

	if (fimc_set_fmt(fimc, DIR_IN, option.in_width, option.in_height))
		return 1;

	if (fimc_set_fmt(fimc, DIR_OUT, option.width, option.height))
		return 1;

	mfc = mfc_create(option.mfc_name);
	if (mfc == NULL)
		return 1;
	chain[2] = mfc;

	if (mfc_set_fmt(mfc, DIR_IN, option.width, option.height))
		return 1;

	if (mfc_set_codec(mfc, DIR_OUT, option.codec))
		return 1;

	if (mfc_set_rate(mfc, option.rate))
		return 1;

	if(option.codec == V4L2_PIX_FMT_H264)
		if(h264_param_init(mfc) < 0)
			return 1;

	output = out_file_create(option.out_name);
	if (output == NULL)
		return 1;
	chain[3] = output;

	if (dev_bufs_create(input, fimc, FIMC_ENC_IN_NBUF, 1))
		return 1;

	if (dev_bufs_create(fimc, mfc, MFC_ENC_IN_NBUF, MFC_MAX_PLANES))
		return 1;

	if (dev_bufs_create(mfc, output, MFC_ENC_OUT_NBUF, MFC_MAX_PLANES))
		return 1;

	//t1 = clock();

	pthread_create(&h264_process_tid, NULL, h264_process_thread,(void *)NULL);

	//pthread_join(process_tid, NULL);
	//t2 = clock();

	//printf("total time:%ldms\n", (t2 - t1)/1000);


	return 0;
}
int h264_exit()
{
	int i;
	for (i = 0; i < array_len(chain); ++i)
		chain[i]->ops->destroy(chain[i]);

	info("h264 encode close");
	return NULL;
}
